package cn.relx.basic.interceptor;

import cn.relx.basic.annotation.PreAuthorize;
import cn.relx.basic.jwt.JwtUtils;
import cn.relx.basic.jwt.Payload;
import cn.relx.basic.jwt.RsaUtils;
import cn.relx.basic.jwt.UserInfo;
import cn.relx.system.mapper.PermissionMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置编码字符集
        response.setCharacterEncoding("utf-8");
        //设置响应参数为json
        response.setContentType("application/json;charset=UTF-8");
        //获取前端请求头中的token信息
        String token = request.getHeader("token");
        //判断前端请求是否携带token，如果携带那么进入判断
        if(!StringUtils.isEmpty(token)){
            // 去redis中拿 用户信息
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            // 判断信息是否存在
            if (null != userInfo.getLogininfo()){
                if (0 == userInfo.getLogininfo().getType()){
                    // 如果是后台人员 需要判断权限
                    // 获取到当前的请求方法
                    HandlerMethod method = (HandlerMethod) handler;
                    // 获取到方法上的注解 PreAuthorize
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (null != annotation){
                        // 方法上配置的sn
                        String sn = annotation.sn();
                        // 查询当前用户拥有哪些权限
//                        List<String> snList =  permissionMapper.findByLogininfoId(userInfo.getLogininfo().getId());
                        List<String> snList = userInfo.getPermissions();
                        if (!snList.contains(sn)){
                            // 不在
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 存在 重置redis的过期时间
//                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //如果能走到这里，说明token为空活着是redis中用户信息为空，那么以未登录进行处理

        //获取到打印流，并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取前端请求头中的token信息
//        String token = request.getHeader("token");
//        //判断前端请求是否携带token，如果携带那么进入判断
//        if(!StringUtils.isEmpty(token)){
//            Object logininfo = redisTemplate.opsForValue().get(token);
//            if(logininfo != null){
//                redisTemplate.opsForValue().set(
//                        token,logininfo,30, TimeUnit.MINUTES
//                );
//                return true;
//            }
//        }
//        //如果能走到这里，说明token为空活着是redis中用户信息为空，那么以未登录进行处理
//        //设置编码字符集
//        response.setCharacterEncoding("utf-8");
//        //设置响应参数为json
//        response.setContentType("application/json;charset=UTF-8");
//        //获取到打印流，并设置响应数据
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
//        writer.flush();
//        writer.close();
//        return false;
//    }
}
